package com.wj.config;

import com.wj.entity.RoleEntity;
import com.wj.mapper.RoleMapper;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WangJin
 * @version 1.0
 * @date 2022/2/12 14:57
 */
@Configuration
public class ShiroConfig {

    @Resource
    private RoleMapper roleMapper;
    /**
     * shiroFilter配置
     *
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设定登陆页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/home"); //设定登陆成功页面
        Map<String, String> filterChainDefinitionMap = new HashMap<String, String>();
        //不需要登录，就可以访问该接口
        filterChainDefinitionMap.put("/visit","anon");
        //必须登录才能访问该接口，采用弹框的形式
        filterChainDefinitionMap.put("/home","authc");

//        //设置order接口只能order角色访问
//        filterChainDefinitionMap.put("/order/*","roles[order]");
//        //设置member接口只能member角色访问
//        filterChainDefinitionMap.put("/member/*","roles[member]");

        List<RoleEntity> roleEntities = roleMapper.selectRoleAll();
        roleEntities.forEach((t)->{
            filterChainDefinitionMap.put(t.getPermissionUrl(),"roles["+t.getRole()+"]");
        });

        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        return shiroFilterFactoryBean;
    }

    /**
     * 注入安全管理器
     * 过滤器
     * @return SecurityManager
     */
    @Bean
    public SecurityManager securityManager() {
        // 将自定义 Realm 加进来
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(Realm);
        return securityManager;
    }
    @Autowired
    private Realm Realm;
}
